package groupby.manage;

import groupby.model.Category;
import groupby.model.Groupby;
import groupby.persistence.GroupCriticismDao;
import groupby.persistence.GroupbyDao;
import groupby.util.Pages;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import user.model.UserDetial;
import user.persistence.UsersDao;
import dic.model.City;
import dic.persistence.DicDao;

public class GroupbyManageImpl implements GroupbyManage {

	private GroupbyDao groupDao = null;
    private GroupCriticismDao  groupbyCDao=null;
	private DicDao dicDao=null;
	private UsersDao usersDao=null;
	public DicDao getDicDao() {
		return dicDao;
	}

	public void setDicDao(DicDao dicDao) {
		this.dicDao = dicDao;
	}

	public GroupbyDao getGroupDao() {
		return groupDao;
	}

	public void setGroupDao(GroupbyDao groupDao) {
		this.groupDao = groupDao;
	}

	public void save(Groupby groupby) {
		this.groupDao.save(groupby);
	}

	/**
	 * 获得当天列表
	 */
	public JSONObject  getGroupbyList(String title,String dateDate,String endDate,String categoryId, Pages page,int cityId) {
		List list = groupDao.getGroupbyList(title, dateDate, endDate,categoryId, page,cityId);
		JSONObject jsonObj = new JSONObject();
		JSONArray jsonArray=new JSONArray();
		try {
			for (int i = 0; i < list.size(); i++) {
				JSONObject jsontemp = new JSONObject();
				Groupby groupby = (Groupby) list.get(i);
				jsontemp.put("checkbox", "<input type=\"checkbox\" name=\"id\" value=\""+groupby.getId()+"\"/>");
				jsontemp.put("title",groupby.getTitle());
				
				City city=dicDao.findCityById(groupby.getCityId());
				jsontemp.put("city", city.getName());
				
				Category category=null;
				
				  if(groupby.getCategoryId()!=null)
				  {
					  category=groupDao.findCategoryById(groupby.getCategoryId());
					  jsontemp.put("category", category.getCategoryName());
				  }else
				  {
					  jsontemp.put("category", "");
				  }
				
				
				jsontemp.put("price", groupby.getPrice().toString());
				jsontemp.put("startTime", groupby.getStartDate());
				jsontemp.put("endTime",groupby.getEndDate());
				jsontemp.put("delete", "<a href=\"javascript:deleteGroupby("+groupby.getId()+")\">删除</a>");
				jsonArray.add(jsontemp);
			}
			jsonObj.put("total", page.getRowCount());
			jsonObj.put("rows", jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
       System.out.println(jsonObj.toString());
		return jsonObj;
	}

	/**
	 * 
	 *排行
	 */

	public List getBeforeList(String id) {
		List list = groupDao.getBeforeList(id);
		return list;
	}
	/**
	 * 删除groupby
	 * @param id
	 * @return
	 */
	public JSONObject delete(String id) {
		 boolean isSuccess=groupDao.delete(id);
		 JSONObject jsonObject=new JSONObject();
		 jsonObject.put("success", isSuccess);
		return jsonObject;
	}
	/**
	 * 获得groupby  Category
	 * @return
	 */
	public JSONObject getCategory(Pages pages,String flag) {
		
		List list = groupDao.getCategory(pages,flag);
		JSONObject jsonObj = new JSONObject();
		JSONArray jsonArray=new JSONArray();
		try {
			for (int i = 0; i < list.size(); i++) {
				JSONObject jsontemp = new JSONObject();
				Category category = (Category) list.get(i);
				jsontemp.put("checkbox", "<input type=\"checkbox\" name=\"id\" value=\""+category.getId()+"\"/>");
				jsontemp.put("title",category.getCategoryName());
				jsontemp.put("id",category.getId());
				jsontemp.put("delete", "<a href=\"javascript:modify("+category.getId()+",\'"+category.getCategoryName()+"\')\">修改</a> <a href=\"javascript:deleteCategory("+category.getId()+")\">删除</a>");
				jsonArray.add(jsontemp);
			}
			jsonObj.put("total", pages.getRowCount());
			jsonObj.put("rows", jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
       
		return jsonObj;
	}
	/**
	 * 添加category
	 * @param category
	 * @return
	 */
	public JSONObject addCategory(Category category) {
		boolean isSuccess=groupDao.add(category);
		 JSONObject jsonObject=new JSONObject();
		 jsonObject.put("success", isSuccess);
		return jsonObject;
	}
	/**
	 * 修改category
	 * @param category
	 * @return
	 */
	public JSONObject editCategory(Category category) {
		boolean isSuccess=groupDao.edit(category);
		 JSONObject jsonObject=new JSONObject();
		 jsonObject.put("success", isSuccess);
		return jsonObject;
	}
	/**
	 * 删除category
	 */
	public JSONObject deleteCategory(String id) {
		boolean isSuccess=groupDao.deleteCategory(id);
		 JSONObject jsonObject=new JSONObject();
		 jsonObject.put("success", isSuccess);
		return jsonObject;
	}
   /**
    * 获得 category select list
    */
	public JSONObject getSelectList(String flag) {
		
		List list = groupDao.getSelectList(flag);
		JSONObject jsonObj = new JSONObject();
		StringBuffer sb=new StringBuffer();
		sb.append("<option id='all'></option>");
		try {
			for (int i = 0; i < list.size(); i++) {
				Category category = (Category) list.get(i);
				sb.append("<option value='"+category.getId()+"'>"+category.getCategoryName()+"</option>");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		jsonObj.put("select",sb.toString());
		return jsonObj;
	}
/**
 * 修改 groupby categoryId
 */
public JSONObject updateGroupby(String id, String categoryId) {
	boolean isSuccess=groupDao.updateGroupby(id,categoryId);
	 JSONObject jsonObject=new JSONObject();
	 jsonObject.put("success", isSuccess);
	return jsonObject;
}
/**
 * 获得所有cateogry list
 * @return
 */
public List getCategoryAll(int flag) {
	   List categoryList=groupDao.getCategoryAll(flag);
	return categoryList;
}

public List getGroupbyTodayListAll(Pages pages,String cityId,String categoryId,String keyword,String sortFlag) {
	List list=groupDao.getGroupbyTodayListAll(pages,cityId,categoryId,keyword,sortFlag);
	List listGroupby=new ArrayList();
	for(int i=0;i<list.size();i++)
	{
		String[] groupbyStr=new String[12];
		Groupby groupby=(Groupby)list.get(i);
		
		groupbyStr[0]=groupby.getId().toString();
		
		
		groupbyStr[1]=groupby.getTitle();
		
		
		groupbyStr[2]=groupby.getPrice().toString();
		groupbyStr[3]=groupby.getOriginalCost().toString();
		groupbyStr[4]=groupby.getDiscountPercent();
		groupbyStr[5]=groupby.getDiscountAmount().toString();
		if(groupby.getTopCount()==null)
		{
			groupbyStr[6]="0";
		}else
		{
			groupbyStr[6]=groupby.getTopCount().toString();
		}
		groupbyStr[7]= groupbyCDao.count(groupby.getId().toString())+"";
		groupbyStr[8]=groupby.getImage();
		groupbyStr[9]=groupby.getEndDate();
		groupbyStr[10]=groupby.getDealUrl();
		UserDetial usersDetial=usersDao.getSingleUser(groupby.getWebsite());
		if(usersDetial==null)
		{
			groupbyStr[11]="<font style='font-weight:bold;color:#982987;'>"+groupby.getWebsite()+"</font>|&nbsp;&nbsp;";
		}else
		{
			groupbyStr[11]="<a style='font-weight:bold;color:#982987;' href='user!groupbyUserPage.action?currentPage=1&userId="+usersDetial.getUserId()+"'>"+groupby.getWebsite()+"</a>|&nbsp;&nbsp;";
		}
		listGroupby.add(groupbyStr);
	}
	
	return listGroupby;
}

public GroupCriticismDao getGroupbyCDao() {
	return groupbyCDao;
}

public void setGroupbyCDao(GroupCriticismDao groupbyCDao) {
	this.groupbyCDao = groupbyCDao;
}
/**
 * top
 */
public JSONObject getTop(String id) {
	 int top=groupDao.getTop(id);
	 JSONObject jsonObject=new JSONObject();
	 jsonObject.put("success", top+"人");
	return jsonObject;
}
/**
 * 获得category by id
 */
public Category findCategoryById(int categoryId) {
	Category category=groupDao.findCategoryById(categoryId);
	return category;
}
/**
 * 获得tags
 */
public String getTags(String path) {
	path=path.replaceAll("%20"," ").replace("/", File.separator).replace("\\",File.separator);
	File file=new File(path);
	
	SAXReader reader = new SAXReader();
	reader.setEncoding("utf-8"); 
	String tags=null;
	Document doc;
	try {
		doc = reader.read(file);
		 tags = doc.selectSingleNode("//tags/taglist").getText().trim();
		
	} catch (DocumentException e) {
		
		e.printStackTrace();
	}
		
	
	return tags;
}
/**
 * 添加tags
 */
public JSONObject addTags(String tag,String path) {

	path=path.replaceAll("%20"," ").replace("/", File.separator).replace("\\",File.separator);
	File file=new File(path);
	
	SAXReader reader = new SAXReader();
	 reader.setEncoding("utf-8"); 
	String tags=null;
	Document doc;
	try {
		doc = reader.read(file);
		
		
		
		 tags = doc.selectSingleNode("//tags/taglist").getText().trim();
		 if(tags==null||tags.equals(""))
		 {
			 doc.selectSingleNode("//tags/taglist").setText("\""+tag+"\"");
		 }else
		 {
			 tag=",\""+tag+"\"";
			 doc.selectSingleNode("//tags/taglist").setText(tags+tag);
		 }
		 OutputFormat format = new OutputFormat("\t", true); 
         format.setEncoding("utf-8");   
          XMLWriter output;
		 output = new XMLWriter(new FileOutputStream(new File(path)), format);
		 output.write(doc);   
           output.close(); 
           doc.clearContent();
        
	} catch (DocumentException e) {
		
		e.printStackTrace();
		 JSONObject josnObject=new JSONObject();
		    josnObject.put("success", false);
		return josnObject;
	}catch (IOException e) {
		
		e.printStackTrace();
		 JSONObject josnObject=new JSONObject();
		    josnObject.put("success", false);
		return josnObject;
	}  
	 
	 JSONObject josnObject=new JSONObject();
	    josnObject.put("success", true);
	return josnObject;
	
}
/**
 * 删除tags
 */
public JSONObject delTags(String tag,String path) {
	path=path.replaceAll("%20"," ").replace("/", File.separator).replace("\\",File.separator);
	File file=new File(path);
	
	SAXReader reader = new SAXReader();
	 reader.setEncoding("utf-8"); 
	String tags=null;
	Document doc;
	try {
		doc = reader.read(file);
		 tags = doc.selectSingleNode("//tags/taglist").getText().trim();
		 if(tags!=null&&tags.indexOf("\""+tag+"\"")==0)
		 {
			 doc.selectSingleNode("//tags/taglist").setText(tags.replaceAll("\""+tag+"\"","").replaceFirst(",",""));
			 
		 }else
		 {
			 tag=",\""+tag+"\"";
			 tags=tags.replaceAll(tag,"");
			 doc.selectSingleNode("//tags/taglist").setText(tags);
		 }
		 OutputFormat format = new OutputFormat("\t", true); 
         format.setEncoding("utf-8");   
          XMLWriter output;
		 output = new XMLWriter(new FileOutputStream(new File(path)), format);
		 output.write(doc);   
           output.close(); 
           doc.clearContent();
        
	} catch (DocumentException e) {
		
		e.printStackTrace();
		 JSONObject josnObject=new JSONObject();
		    josnObject.put("success", false);
		return josnObject;
	}catch (IOException e) {
		
		e.printStackTrace();
		 JSONObject josnObject=new JSONObject();
		    josnObject.put("success", false);
		return josnObject;
	}  
	 
	 JSONObject josnObject=new JSONObject();
	    josnObject.put("success", true);
	return josnObject;
}
/**
 *获得单个团购
 */
public Groupby criticismGroupbyId(int groupbyId) {
	return groupDao.criticismGroupbyId(groupbyId);
	
}

public UsersDao getUsersDao() {
	return usersDao;
}

public void setUsersDao(UsersDao usersDao) {
	this.usersDao = usersDao;
}
/**
 * 获得团购用户的团购用户的信息
 */
public List<Groupby> getGroupbyTodayListAll(String username, Pages pages,
		String categoryId, String sort,String keyword,int cityId) {
	List list=groupDao.getGroupbyTodayListAll(username,pages,categoryId,sort,keyword,cityId);
	List listGroupby=new ArrayList();
	for(int i=0;i<list.size();i++)
	{
		String[] groupbyStr=new String[12];
		Groupby groupby=(Groupby)list.get(i);
		groupbyStr[0]=groupby.getId().toString();
		groupbyStr[1]=groupby.getTitle();
		groupbyStr[2]=groupby.getPrice().toString();
		groupbyStr[3]=groupby.getOriginalCost().toString();
		groupbyStr[4]=groupby.getDiscountPercent();
		groupbyStr[5]=groupby.getDiscountAmount().toString();
		if(groupby.getTopCount()==null)
		{
			groupbyStr[6]="0";
		}else
		{
			groupbyStr[6]=groupby.getTopCount().toString();
		}
		groupbyStr[7]= groupbyCDao.count(groupby.getId().toString())+"";
		groupbyStr[8]=groupby.getImage();
		groupbyStr[9]=groupby.getEndDate();
		groupbyStr[10]=groupby.getDealUrl();
		UserDetial usersDetial=usersDao.getSingleUser(groupby.getWebsite());
		if(usersDetial==null)
		{
			groupbyStr[11]="<font style='font-weight:bold;color:#982987;'>"+groupby.getWebsite()+"</font>|&nbsp;&nbsp;";
		}else
		{
			groupbyStr[11]="<a style='font-weight:bold;color:#982987;' href='user!groupbyUserPage.action?userId="+usersDetial.getUserId()+"'>"+groupby.getWebsite()+"</a>|&nbsp;&nbsp;";
		}
		listGroupby.add(groupbyStr);
	}
	return listGroupby;
}

/**
 * 评价团购用户
 */
public UserDetial criticismGroupbyUserId(int groupbyUserId) {
	return groupDao.criticismGroupbyUserId(groupbyUserId);
	
}
/**
 * 
 * 获得往期团购列表
 * 
 */
@SuppressWarnings("unchecked")
public List oldGroupbyList(String categoryId, String keyword, String sort,Pages pages,int cityId) {

	List list=groupDao.oldGroupbyList(pages,cityId,"","");
	List listOld=new ArrayList();
	for(int k=0;k<list.size();k++)
	{
		Object[] obj=new Object[3];
		 obj[0]=((Object[])list.get(k))[0];
		 obj[1]=((Object[])list.get(k))[2];
		 
		 String startTime=obj[1]+" 00:00:00";
		 String endTime=obj[1]+" 23:59:59";
		 Pages page=new Pages();
		 page.setCurrentPage(1);
		 page.setPageSize(4);
		 List listGroupby=groupDao.oldGroupbyListByPage( categoryId,  keyword,startTime,endTime, sort,page,cityId,"");
		 List listGroupbyTemp=new ArrayList();
		 for(int i=0;i<listGroupby.size();i++)
			{
				String[] groupbyStr=new String[12];
				Groupby groupby=(Groupby)listGroupby.get(i);
				groupbyStr[0]=groupby.getId().toString();
				groupbyStr[1]=groupby.getTitle();
				groupbyStr[2]=groupby.getPrice().toString();
				groupbyStr[3]=groupby.getOriginalCost().toString();
				groupbyStr[4]=groupby.getDiscountPercent();
				groupbyStr[5]=groupby.getDiscountAmount().toString();
				if(groupby.getTopCount()==null)
				{
					groupbyStr[6]="0";
				}else
				{
					groupbyStr[6]=groupby.getTopCount().toString();
				}
				groupbyStr[7]= groupbyCDao.count(groupby.getId().toString())+"";
				groupbyStr[8]=groupby.getImage();
				groupbyStr[9]=groupby.getEndDate();
				groupbyStr[10]=groupby.getDealUrl();
				UserDetial usersDetial=usersDao.getSingleUser(groupby.getWebsite());
				if(usersDetial==null)
				{
					groupbyStr[11]="<font style='font-weight:bold;color:#982987;'>"+groupby.getWebsite()+"</font>|&nbsp;&nbsp;";
				}else
				{
					groupbyStr[11]="<a style='font-weight:bold;color:#982987;' href='user!groupbyUserPage?id="+usersDetial.getUserId()+"'>"+groupby.getWebsite()+"</a>|&nbsp;&nbsp;";
				}
				listGroupbyTemp.add(groupbyStr);
			}
		 obj[2]=listGroupbyTemp;
		 listOld.add(obj);
	}
	return listOld;
}

public List oldGroupbyListByPage(String categoryId, String keyword,
		String startTime, String endTime, String sort, Pages pages, int cityId,String username) {
	List listGroupby=groupDao.oldGroupbyListByPage( categoryId,  keyword,startTime,endTime, sort,pages,cityId,username);
	List listGroupbyTemp=new ArrayList();
	 for(int i=0;i<listGroupby.size();i++)
		{
			String[] groupbyStr=new String[12];
			Groupby groupby=(Groupby)listGroupby.get(i);
			groupbyStr[0]=groupby.getId().toString();
			groupbyStr[1]=groupby.getTitle();
			groupbyStr[2]=groupby.getPrice().toString();
			groupbyStr[3]=groupby.getOriginalCost().toString();
			groupbyStr[4]=groupby.getDiscountPercent();
			groupbyStr[5]=groupby.getDiscountAmount().toString();
			if(groupby.getTopCount()==null)
			{
				groupbyStr[6]="0";
			}else
			{
				groupbyStr[6]=groupby.getTopCount().toString();
			}
			groupbyStr[7]= groupbyCDao.count(groupby.getId().toString())+"";
			groupbyStr[8]=groupby.getImage();
			groupbyStr[9]=groupby.getEndDate();
			groupbyStr[10]=groupby.getDealUrl();
			UserDetial usersDetial=usersDao.getSingleUser(groupby.getWebsite());
			if(usersDetial==null)
			{
				groupbyStr[11]="<font style='font-weight:bold;color:#982987;'>"+groupby.getWebsite()+"</font>|&nbsp;&nbsp;";
			}else
			{
				groupbyStr[11]="<a style='font-weight:bold;color:#982987;' href='user!groupbyUserPage?id="+usersDetial.getUserId()+"'>"+groupby.getWebsite()+"</a>|&nbsp;&nbsp;";
			}
			listGroupbyTemp.add(groupbyStr);
		}
	return listGroupbyTemp;
}
/**
 * 获得团购用户的团购活动
 */
public List myGroupby(Pages pages, String keyword, String sort, String username,int cityId) {
	List list=groupDao.myGroupby( pages,keyword,sort,  username,cityId);
	List listGroupby=new ArrayList();
	for(int i=0;i<list.size();i++)
	{
		String[] groupbyStr=new String[12];
		Groupby groupby=(Groupby)list.get(i);
		groupbyStr[0]=groupby.getId().toString();
		groupbyStr[1]=groupby.getTitle();
		groupbyStr[2]=groupby.getPrice().toString();
		groupbyStr[3]=groupby.getOriginalCost().toString();
		groupbyStr[4]=groupby.getDiscountPercent();
		groupbyStr[5]=groupby.getDiscountAmount().toString();
		if(groupby.getTopCount()==null)
		{
			groupbyStr[6]="0";
		}else
		{
			groupbyStr[6]=groupby.getTopCount().toString();
		}
		groupbyStr[7]= groupbyCDao.count(groupby.getId().toString())+"";
		groupbyStr[8]=groupby.getImage();
		groupbyStr[9]=groupby.getEndDate();
		groupbyStr[10]=groupby.getDealUrl();
		UserDetial usersDetial=usersDao.getSingleUser(groupby.getWebsite());
		if(usersDetial==null)
		{
			groupbyStr[11]="<font style='font-weight:bold;color:#982987;'>"+groupby.getWebsite()+"</font>|&nbsp;&nbsp;";
		}else
		{
			groupbyStr[11]="<a style='font-weight:bold;color:#982987;' href='user!groupbyUserPage?id="+usersDetial.getUserId()+"'>"+groupby.getWebsite()+"</a>|&nbsp;&nbsp;";
		}
		listGroupby.add(groupbyStr);
	}
	return listGroupby;
}
/**
 * 获得我的往期团购活动
 */
public List oldGroupbyList(String keyword, String sort, Pages pages,
		String username,int cityId) {
	List list=groupDao.oldGroupbyList(pages,-1, username,cityId+"");
	List listOld=new ArrayList();
	for(int k=0;k<list.size();k++)
	{
		Object[] obj=new Object[3];
		 obj[0]=((Object[])list.get(k))[0];
		 obj[1]=((Object[])list.get(k))[2];
		 
		 String startTime=obj[1]+" 00:00:00";
		 String endTime=obj[1]+" 23:59:59";
		 Pages page=new Pages();
		 page.setCurrentPage(1);
		 page.setPageSize(4);
		 List listGroupby=groupDao.oldGroupbyListByPage( keyword,startTime,endTime, sort,page,username);
		 List listGroupbyTemp=new ArrayList();
		 for(int i=0;i<listGroupby.size();i++)
			{
				String[] groupbyStr=new String[12];
				Groupby groupby=(Groupby)listGroupby.get(i);
				groupbyStr[0]=groupby.getId().toString();
				groupbyStr[1]=groupby.getTitle();
				groupbyStr[2]=groupby.getPrice().toString();
				groupbyStr[3]=groupby.getOriginalCost().toString();
				groupbyStr[4]=groupby.getDiscountPercent();
				groupbyStr[5]=groupby.getDiscountAmount().toString();
				if(groupby.getTopCount()==null)
				{
					groupbyStr[6]="0";
				}else
				{
					groupbyStr[6]=groupby.getTopCount().toString();
				}
				groupbyStr[7]= groupbyCDao.count(groupby.getId().toString())+"";
				groupbyStr[8]=groupby.getImage();
				groupbyStr[9]=groupby.getEndDate();
				groupbyStr[10]=groupby.getDealUrl();
				UserDetial usersDetial=usersDao.getSingleUser(groupby.getWebsite());
				if(usersDetial==null)
				{
					groupbyStr[11]="<font style='font-weight:bold;color:#982987;'>"+groupby.getWebsite()+"</font>|&nbsp;&nbsp;";
				}else
				{
					groupbyStr[11]="<a style='font-weight:bold;color:#982987;' href='user!groupbyUserPage?id="+usersDetial.getUserId()+"'>"+groupby.getWebsite()+"</a>|&nbsp;&nbsp;";
				}
				listGroupbyTemp.add(groupbyStr);
			}
		 obj[2]=listGroupbyTemp;
		 listOld.add(obj);
	}
	return listOld;
}
/**
 * 获得相同团购
 */
public boolean isFindGroupby(String text,int cityId) {
	boolean isFind=groupDao.isFindGroupby(text,cityId);
	return isFind;
}


}
